<!-- src/components/UserInfoBar.vue -->
<script setup lang="ts">
import { computed } from 'vue'
import { useUserStore } from '@/stores/user'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, SwitchButton } from '@element-plus/icons-vue' // 引入缺失的图标组件

const userStore = useUserStore()
const router = useRouter()

// 获取用户信息
const user = computed(() => userStore.user)

// 用户头像URL处理
const avatarUrl = computed(() => {
  if (user.value?.avatarUrl) {
    return user.value.avatarUrl
  }
  // 默认头像
  return 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
})

// 退出登录
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要退出登录吗？',
      '退出登录',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    // 清除用户信息
    userStore.clearUser()
    // 跳转到登录页
    router.push('/login')
    ElMessage.success('已退出登录')
  } catch (error: unknown) {

    // 用户取消操作，无需特殊处理
    console.log('用户取消退出登录' + error)
  }
}

// 跳转到个人中心
const goToProfile = () => {
  router.push('/profile')
}
</script>

<template>
  <div class="user-info-bar">
    <div class="user-info" v-if="user">
      <el-dropdown>
        <div class="user-dropdown">
          <el-avatar :src="avatarUrl" size="small" />
          <span class="username">{{ user.nickname || user.username }}</span>
        </div>

        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="goToProfile">
              <el-icon><User /></el-icon>
              个人中心
            </el-dropdown-item>
            <el-dropdown-item @click="handleLogout">
              <el-icon><SwitchButton /></el-icon>
              退出登录
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>

    <div class="user-info-placeholder" v-else>
      <el-skeleton :rows="0" animated style="width: 120px;">
        <template #template>
          <div style="display: flex; align-items: center; gap: 10px;">
            <el-skeleton-item variant="circle" style="width: 32px; height: 32px;" />
            <el-skeleton-item variant="text" style="width: 80px; height: 20px;" />
          </div>
        </template>
      </el-skeleton>
    </div>
  </div>
</template>

<style scoped>
.user-info-bar {
  display: flex;
  align-items: center;
  height: 100%;
  padding-right: 20px;
}

.user-dropdown {
  display: flex;
  align-items: center;
  cursor: pointer;
  gap: 8px;
  padding: 5px 10px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.user-dropdown:hover {
  background-color: #f5f7fa;
}

.username {
  font-size: 14px;
  color: #606266;
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.user-info-placeholder {
  padding: 0 10px;
}
</style>
